var app = getApp();
var util = require("../../utils/util.js");
var siteinfo = require('../../siteinfo.js');
var answerList = []; //本地答案集合：id+value+answer+score
var answerListToService = []; //提交服务器答案合集：id+value
//实现单选、多选
Page({
  data: {
    index: 0, // 题目序列
    tpaperId:null,
    questionList:[],
    isShowAnswer:false, //是否展示答案
    ebatch:null,//考试批次信息
    stuInfo:null,//考生信息
    submittingHidden:true,
    answerList:[]
  },
  onLoad: function(options) {

    var _this = this
    wx.setNavigationBarTitle({
      title: wx.getStorageSync('ebatchInfo').name
    })
    _this.setData({
      ebatch:wx.getStorageSync('ebatchInfo'),
      stuInfo:wx.getStorageSync('stuInfo')
    })
    this.getPractice()
  },
 onShow:function(){

 },
 getIndex: function(e){
  var value = e.detail.value;
  this.setData({
    inputIndex: value
  });
},
  //获取题目数据
  getPractice: function() {
    var _this = this
    app._post_form(siteinfo.selTeacherExaminationPaper, {
       id: wx.getStorageSync('ebatchInfo').id
    }, function(result) {
      var practiceList = result.data.questions
      util.calculateTime(_this, wx.getStorageSync('ebatchInfo').endTime)
      app.showError(practiceList.length)
      for (var i = 0; i < practiceList.length; i++) {
        practiceList[i].options = practiceList[i].options.split(";;")
        practiceList[i].checked = false
        for (var j = 0; j < practiceList[i].options.length; j++) {
          practiceList[i].options[j] = {
            "score": 0,
            "code": practiceList[i].options[j].substring(0, 1),
            "content": practiceList[i].options[j].substring(2, practiceList[i].options[j].length),
            "checked":false
          }
        }
      }
      _this.setData({
        questionList: practiceList, // 拿到答题数据
        tpaperId: result.data.id
      })
    })
  },
  /*
   * 单选事件
   */
  radioChange: function(e) {
    var _this = this
    var questionList = _this.data.questionList
    var index = _this.data.index
    for (var i = 0; i <questionList.length; i++){
      if (questionList[index].id == questionList[i].id){
        for (var j = 0; j < questionList[index].options.length; j ++){
          //渲染答卷选项
          if (e.detail.value ==questionList[index].options[j].code){
            questionList[index].options[j].checked = true
          }else{
            questionList[index].options[j].checked = false
          }
        }
          questionList[i].value = e.detail.value
        }
    }
    _this.setData({
      questionList:questionList
    })
  },
  /*
   * 多选事件
   */
  checkboxChange: function(e) {
    var _this = this
    var questionList = _this.data.questionList
    var index = _this.data.index
    for (var i = 0; i < questionList.length; i++) {
      if (questionList[index].id == questionList[i].id) {
        for (var j = 0; j < questionList[index].options.length; j++) {
          questionList[index].options[j].checked = false
          for (var b = 0; b < e.detail.value.length;b++){
            //渲染答卷选项
            if (e.detail.value[b] == questionList[index].options[j].code) {
              questionList[index].options[j].checked = true
            }
          }
          questionList[i].value = e.detail.value
        }
      }
    }
    _this.setData({
      questionList: questionList
    })
  },
  goTo:function(){
    var _this=this
    var i = _this.data.inputIndex
    if(i>=1&&i<=_this.data.questionList.length){
      _this.setData({
        index: i-1
      })
    }else{
      _this.setData({
        inputIndex: _this.data.index+1
      })
      return ;
    }
  },
  // 上一题
  prev: function() {
    var _this = this
    if (_this.data.index != 0) {
      // 渲染下一题
      _this.setData({
        index: _this.data.index - 1
      })
    }
  },
  sumitPaper:function(){
    var _this = this
    var _app = app
    _this.setData({
      submittingHidden:false
    })
    //格式化答卷格式id+value
    answerList = []; //本地答案集合：id+value+answer+score
    answerListToService = []; //提交服务器答案合集：id+value
    for (var i = 0; i < _this.data.questionList.length;i++){
      if (typeof (_this.data.questionList[i].value) == 'object') {
        var bb =''
        for (var j = 0; j < _this.data.questionList[i].value.length;j++){
          bb += _this.data.questionList[i].value[j] + ';;'
          }
          answerListToService.push({ id: _this.data.questionList[i].id, value: bb});
          answerList.push({ id: _this.data.questionList[i].id, value: bb, answer:  _this.data.questionList[i].answers, score: _this.data.questionList[i].score});
        }else{
          console.log(_this.data.questionList[i].value+" "+_this.data.questionList[i].answers)
          answerListToService.push({ id: _this.data.questionList[i].id, value: _this.data.questionList[i].value});
          answerList.push({ id: _this.data.questionList[i].id, value: _this.data.questionList[i].value, answer:  _this.data.questionList[i].answers, score: _this.data.questionList[i].score });
        } 
    }
    wx.request({
      url:siteinfo.selAnswerSheet,
      header:{
        'content-type': 'application/x-www-form-urlencoded'
      },
      method:"POST",
      data:{
        stuSignId: _this.data.stuInfo.stuSignId,
        epaperId: _this.data.tpaperId,
        answerList:JSON.stringify(answerListToService),
        code: _this.data.stuInfo.cookieCode
      },
      success:function(result){
        _this.setData({
          submittingHidden:true
        })
        if (result.data.code == 0) {
                      //计算总分数
                      var allScore = 0;
                      for (var i = 0; i <= answerList.length - 1; i++) {
                          //单选，判断
                        if(answerList[i].value !=undefined){
                          if (answerList[i].value.toString().indexOf(";;") == -1) {
                            if (answerList[i].value == answerList[i].answer) {
                              allScore = allScore + answerList[i].score * 1
                            }
                          } else {
                          //多选
                          var answerList1 = answerList[i].answer.split(";;").sort();
                          var b = true;
                          var c = '';
                          var d = '';
                            var valueList = answerList[i].value.split(";;");
                            //数组重新排序
                            var valueList1 =valueList.slice(0,valueList.length-1).sort()
                            if (valueList1.length == answerList1.length) {
                              for (var a = 0; a < valueList1.length; a++) {
                                c+=valueList1[a]+" "
                                if (a<answerList1.length) {
                                  d+=answerList1[a]+" "
                                  if(valueList1[a] != answerList1[a])
                                    b = false;
                                }
                            }
                            
                          }else{
                            b = false;
                            for (var a = 0; a < answerList1.length; a++) {
                              d+=answerList1[a]+" "
                            }
                            for (var a = 0; a < valueList1.length; a++) {
                              c+=valueList1[a]+" "
                            }
                          }
                          answerList[i].value = c.substring(0,c.length-1);
                          answerList[i].answer = d.substring(0,d.length-1);
                          if (b == true) {
                            allScore = allScore + answerList[i].score * 1
                          }
                        }
                      }else{
                        if(answerList[i].answer.toString().indexOf(";;") != -1){
                          var answerList1 = answerList[i].answer.split(";;").sort();
                          var d= ''
                          for (var a = 0; a < answerList1.length; a++) {
                            d+=answerList1[a]+" "
                          }
                          answerList[i].answer = d.substring(0,d.length-1);
                        }
                        
                      }
                    }
                      _this.setData({
                        answerList:answerList
                      })
                      wx.showModal({
                        title: '提示',
                        content: '您的总分为'+allScore+'分',
                        showCancel:false,
                        success: function(res) {
                            if(res.confirm){  
                              answerList = []
                                _this.setData({
                                isShowAnswer:true
                                })
                            }
                        }
                      })
      } else {
        _app.showError(result.data.msg)
      }
      }
    })
  },
  /*
   * 下一题/提交 按钮
   */
  nextSubmit: function() {
    var _this = this
    _this.setData({
      prevBtn: true
    })
    // 判断是不是最后一题
    if (_this.data.index < _this.data.questionList.length - 1) {
      // 渲染下一题
      _this.setData({
        index: _this.data.index + 1
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '确定要提交答卷？',
        success: function(res) {
          if (res.confirm) {
            _this.sumitPaper()
          }
        }
      })
    }
  },
})